package com.world.blog.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import com.world.blog.domain.BlogArticle;
import com.world.blog.enums.ArticleStatusEnums;
import com.world.blog.factory.BlogAsyncManager;
import com.world.common.constant.CacheConstants;
import com.world.common.core.domain.entity.SysUser;
import com.world.common.core.redis.RedisCache;
import com.world.common.core.service.BaseService;
import com.world.common.utils.DateUtils;
import com.world.common.utils.SecurityUtils;
import com.world.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.world.blog.mapper.ArticleMapper;
import com.world.blog.service.IBlogArticleService;

/**
 * 文章Service业务层处理
 * 
 * @author LiJunXi
 * @date 2025-05-19
 */
@Service
public class BlogArticleServiceImpl extends BaseService<BlogArticle> implements IBlogArticleService
{
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private BlogAsyncManager blogAsyncManager;

    /**
     * 查询文章
     * 
     * @param articleId 文章主键
     * @return 文章
     */
    @Override
    public BlogArticle selectArticleByArticleId(Long articleId)
    {
        BlogArticle blogArticle = articleMapper.selectArticleByArticleId(articleId);
        SysUser user = userService.selectUserById(blogArticle.getUserId());
        fillArticleUiParams(blogArticle, user);
        blogAsyncManager.addArticleViewsCount(blogArticle.getArticleId());
        return blogArticle;
    }

    private void fillArticleUiParams(BlogArticle blogArticle, SysUser user) {
        blogArticle.setUserName(user.getUserName());
        blogArticle.setNickName(user.getNickName());
        blogArticle.setAvatar(user.getAvatar());
        blogArticle.setViewsCount(getArticleViewsCount(blogArticle.getArticleId()) + 1);
    }

    @Override
    public Integer getArticleViewsCount(Long articleId) {
        Integer viewsCount = redisCache.getCacheObject(CacheConstants.BLOG_ARTICLE_VIEWS_COUNT + articleId);
        return Objects.isNull(viewsCount) ? 0 : viewsCount;
    }

    /**
     * 查询文章列表
     * 
     * @param blogArticle 文章
     * @return 文章
     */
    @Override
    public List<BlogArticle> selectArticleList(BlogArticle blogArticle)
    {
        if (!SecurityUtils.isAnonymous() && !SecurityUtils.isBlogAdmin() && !SecurityUtils.isAdmin()) {
            blogArticle.setUserId(SecurityUtils.getUserId());
        }
        List<BlogArticle> blogArticles = articleMapper.selectArticleList(blogArticle);
        List<Long> userIds = blogArticles.stream().map(BlogArticle::getUserId).collect(Collectors.toList());
        Map<Long, SysUser> userMap = userService.selectUserList(userIds)
                .stream()
                .collect(Collectors.toMap(SysUser::getUserId, Function.identity()));

        return pageList2CustomList(blogArticles, (List<BlogArticle> list)-> {
            return list.stream().map(item -> {
                SysUser user = userMap.get(item.getUserId());
                fillArticleUiParams(item, user);
                return item;
            }).collect(Collectors.toList());
        });
    }

    /**
     * 新增文章
     * 
     * @param blogArticle 文章
     * @return 结果
     */
    @Override
    public int insertArticle(BlogArticle blogArticle)
    {
        blogArticle.checkSaveParams();
        fillArticleSaveParams(blogArticle);
        return articleMapper.insertArticle(blogArticle);
    }

    private void fillArticleSaveParams(BlogArticle blogArticle) {
        blogArticle.setUserId(SecurityUtils.getUserId());
        blogArticle.setCreateTime(DateUtils.getNowDate());
        if (StrUtil.isEmpty(blogArticle.getSummary()) && StrUtil.isNotEmpty(blogArticle.getMdContent())) {
            blogArticle.setSummary(getSummaryByMdContent(blogArticle.getMdContent()));
        }
        blogArticle.setCollectCount(0);
        blogArticle.setViewsCount(0);
        blogArticle.setCommentCount(0);
        blogArticle.setLikeCount(0);
        blogArticle.setStatus(ArticleStatusEnums.ON.getKey());
    }

    public String getSummaryByMdContent(String mdContent){
        int count = 0;
        // 提取前255个字符
        StringBuffer result = new StringBuffer();
        for(int i = 0; i < mdContent.length(); i++){
            if (count == 255) {
                break;
            }
            char word = mdContent.charAt(i);
            if (word == '*' || word == '-'|| word == '>' || word == '`' || word == '|' || word == '~' || word == '#'){
                continue;
            }
            count ++;
            result.append(word);
        }
        return result.toString();
    }

    /**
     * 修改文章
     * 
     * @param blogArticle 文章
     * @return 结果
     */
    @Override
    public int updateArticle(BlogArticle blogArticle)
    {
        blogArticle.setUpdateTime(DateUtils.getNowDate());
        return articleMapper.updateArticle(blogArticle);
    }

    /**
     * 批量删除文章
     * 
     * @param articleIds 需要删除的文章主键
     * @return 结果
     */
    @Override
    public int deleteArticleByArticleIds(Long[] articleIds)
    {
        return articleMapper.deleteArticleByArticleIds(articleIds);
    }

    /**
     * 删除文章信息
     * 
     * @param articleId 文章主键
     * @return 结果
     */
    @Override
    public int deleteArticleByArticleId(Long articleId)
    {
        return articleMapper.deleteArticleByArticleId(articleId);
    }

    @Override
    public void synchronousViewsCount() {
        Collection<String> keys = redisCache.keys(CacheConstants.BLOG_ARTICLE_VIEWS_COUNT + "*");
    }
}
